import datetime
import json

from fastapi import APIRouter, WebSocket, WebSocketDisconnect
import asyncio

from Model.SqlDef.commonText import get_commonText_Search_By_keywords

# 创建 WebSocket 路由
mysocket_response_pool = APIRouter(prefix='/response_socket/response/pool', tags=['response_sockets'])

# 定义消息处理器函数
async def handle_ping(websocket: WebSocket, data: str):
    """处理 'ping' 消息的逻辑"""
    await websocket.send_text(json.dumps("pong"))
async def handle_searcharticle(websocket: WebSocket, data:dict):
    """处理 '文章搜索' 消息的逻辑"""
    data=data.get('payload',{})

    articledata=get_commonText_Search_By_keywords(userid=data.get('userid',0), keywords=data.get('keywords'), limit=data.get('limit'))

    message = {"type": "article_search", "status": "success", "payload": {"data": articledata}}

    await websocket.send_text(json.dumps(message))
async  def handle_default(websocket: WebSocket, data: str):
    await websocket.send_text(data)

# 消息处理器映射表
MESSAGE_HANDLERS = {
    "ping": handle_ping,
    'article':handle_searcharticle
}


@mysocket_response_pool.websocket('/search/article')
async def websocket_search_article(websocket: WebSocket):
    await websocket.accept()  # 接受 WebSocket 连接
    try:
        while True:
            try:
                # 加载的数据为{data:,payload}
                # 设置超时时间为 30 秒，等待客户端发送消息
                data =json.loads( await asyncio.wait_for(websocket.receive_text(), timeout=30.0))
                # 根据消息类型选择处理器
                handler = MESSAGE_HANDLERS.get(data.get('type','NONE'), handle_default)
                await handler(websocket, data)

            except asyncio.TimeoutError:
                # 如果超过 30 秒未收到消息，关闭连接
                await  websocket.send_text(json.dumps({'error': 'Timeout'}))
                await websocket.close()
                break
    except WebSocketDisconnect:
        # 客户端断开连接时捕获异常
        pass